package nettyteach.endecoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * 服务器端启动类
 */
public class AppServerEnDeCoder {
    private int port;
    public AppServerEnDeCoder(int port){
        this.port=port;
    }
    public void run() throws  Exception{
//        EventLoopGroup group=new NioEventLoopGroup();//netty的reactor线程池，初始化一个数组
        //负责接收客户端的连接
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        //负责处理消息传输io
        EventLoopGroup workerGroup= new NioEventLoopGroup();
        try{
            //用于启动NIO服务
            ServerBootstrap b=new ServerBootstrap();
            b.group(bossGroup,workerGroup)
                    //通过工厂方法涉及模式实例化一个channel
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    //最大保持连接数128，option主要针对boss线程组
                    .option(ChannelOption.SO_BACKLOG,128)
                    //启动心跳保活机制，主要针对worker线程组
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new InitializerServerEndeCoder());
            //绑定服务器，该实例将提供有关io操作的结果或状态的信息
            ChannelFuture channelFuture=b.bind().sync();
            System.out.println("在"+channelFuture.channel().localAddress()+"上开启监听");
            //阻塞操作，closeFuture()开启了一个channel的监听器（这期间channel在进行各项工作），直到链路断开
           channelFuture.channel().closeFuture().sync();
        }finally {
            //关闭所有EventLoopGroup并释放所有资源，包括所有创建的线程
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();

        }
    }

    public static void main(String[] args) throws Exception {

        new AppServerEnDeCoder(18080).run();
    }
}
